<script setup>
import lottie from 'lottie-web';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
const cxt = getCurrentInstance() // context === vue2 this
const bus = cxt.appContext.config.globalProperties.$bus
const lottieContainer = ref(null);
const animation = ref(null);
let animationTriggered = ref(false); // 用来确保动画只触发一次


watch(animationTriggered, (val) => {
  if (val) {
    // animation.value.stop() // 有bug不起作用
  }
});

onMounted(() => {
  gsap.registerPlugin(ScrollTrigger);

  animation.value = lottie.loadAnimation({
    container: lottieContainer.value,
    renderer: 'svg',
    loop: false,
    autoplay: false,
    path: `https://kanekikeh.online/A/lotties/AiWord_pink.json`,
    fps: 60
  });

  const scrollTrigger = ScrollTrigger.create({
    trigger: lottieContainer.value,
    start: 'top center',
    end: 'center center',
    scrub: 1,
    onUpdate: self => {
      const progress = self.progress;
      const totalFrames = animation.value.totalFrames;
      const frame = Math.floor(progress * totalFrames);
      animation.value.goToAndStop(frame, true);
    }
  });

  if (!animationTriggered.value) {
    animation.value.addEventListener('DOMLoaded', () => {
      scrollTrigger.end = `+=${animation.value.totalFrames / 30}`;
    });
  }

  animation.value.addEventListener('enterFrame', () => {
    const currentFrame = animation.value.currentFrame;
    // 当帧数达到60且动画尚未被触发
    if (currentFrame >= 65 && !animationTriggered.value) {
      setTimeout(() => {
        animationTriggered.value = true; // 标记动画为已触发
        bus.emit('isRenderTemplate', animationTriggered.value)
      }, 500);
      gsap.to(lottieContainer.value, {
        // scale: 0.3, // 缩小到50%
        // yPercent: -80, // 向上移动30%
        // xPercent: -90,
        opacity: 0.2,
        duration: 1, // 动画持续时间为1秒
        ease: "Power1 inOut" // 使用缓动函数使过渡更平滑
      });
    }
  });
});
</script>
<template>
  <div ref="lottieContainer" class="lotties"></div>

</template>

<style scoped lang="scss">
.lotties {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: transparent;
}
</style>